# -*- coding: utf-8 -*-
"""
UI Product
Provide Product related forms/widgets
"""

#---------------------------------------------------------------------------
# Copyright (c) 2014 Ahmad Ghulam Zakiy <ghulam.zakiy@gmail.com>
# License: GPL3
#
# This file is part of SimpleStore
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#---------------------------------------------------------------------------

from PySide import QtCore, QtGui
from ui.widgets import tabbedWidget, searchLineEdit
from lib import format
from lib.view import tableView
from lib.model import tableModel
import qrc

class productWidget(tabbedWidget):

    def __init__(self, database, parent=None):

        super(productWidget, self).__init__(database, parent)

        self.setObjectName("productWidget")

        # Tab-tab yang akan dipakai
        self.tabs.table = QtGui.QWidget()
        self.tabs.table.setObjectName("tabProduk")
        self.addTab(self.tabs.table, "&Produk")

        self.tabs.kategori = QtGui.QWidget()
        self.tabs.kategori.setObjectName("tabKategori")
        self.addTab(self.tabs.kategori, "&Kategori")

        self.tabs.table.tableName = 'view_produk_terkini'
        self.tabs.table.tableHeaderList = self.database.getTableFields(self.tabs.table.tableName)
        
        # search bar
        self.searchGridLayout = QtGui.QGridLayout()
        self.searchGridLayout.setContentsMargins(0, 5, 0, 0)
        self.searchGridLayout.setObjectName("searchGridLayout")
        
        self.searchLabel = QtGui.QLabel("&Search", self.tabs.table)
        self.searchLabel.setObjectName("searchLabel")
        self.searchGridLayout.addWidget(self.searchLabel, 0, 0, 1, 1)

        self.searchLineEdit = searchLineEdit(self.tabs.table)
        self.searchLineEdit.setObjectName("searchLineEdit")
        self.searchGridLayout.addWidget(self.searchLineEdit, 0, 1, 1, 1)
        self.searchLabel.setBuddy(self.searchLineEdit)
        
        self.searchButton = QtGui.QPushButton("&Tampilkan", self.tabs.table)
        self.searchButton.setObjectName("searchButton")
        self.searchGridLayout.addWidget(self.searchButton, 0, 2, 1, 1)

        self.searchGridLayout.setColumnMinimumWidth(4, 6)

        self.clearSearchButton = QtGui.QPushButton("&Hapus", self.tabs.table)
        self.clearSearchButton.setObjectName("clearSearchButton")
        self.searchGridLayout.addWidget(self.clearSearchButton, 0, 3, 1, 1)
        
        # model
        self.tabs.table.model = tableModel(self.database)
        self.tabs.table.model.setTable(self.tabs.table.tableName)
        #self.tabs.table.model.setPaging(True)
        self.tabs.table.model.loadModel()

        # bottom buttonBox
        self.tabs.table.bottomButtonBox = QtGui.QDialogButtonBox(self)
        self.tabs.table.bottomButtonBox.setObjectName("bottomButtonBox")
        self.tabs.table.bottomButtonBox.setOrientation(QtCore.Qt.Horizontal)
        self.tabs.table.bottomButtonCancel = self.tabs.table.bottomButtonBox.addButton(QtGui.QDialogButtonBox.Cancel)
        self.tabs.table.bottomButtonOk = self.tabs.table.bottomButtonBox.addButton(QtGui.QDialogButtonBox.Ok)
        self.tabs.table.bottomButtonRefresh = self.tabs.table.bottomButtonBox.addButton("Refresh", QtGui.QDialogButtonBox.ResetRole)

        # view
        self.tabs.table.view = tableView(self.tabs.table)
        self.tabs.table.view.setObjectName("tableView")
        self.tabs.table.view.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.tabs.table.view.setSortingEnabled(True)
        self.tabs.table.view.setAlternatingRowColors(True)
        self.tabs.table.view.setModel(self.tabs.table.model.model)
        self.tabs.table.view.hideColumns(['Nota'])
        self.tabs.table.view.verticalHeader().hide()
        self.tabs.table.view.resizeColumnsToContents()
        self.tabs.table.view.resizeRowsToContents()
        self.tabs.table.view.horizontalHeader().setStretchLastSection(True)
        self.tabs.table.view.horizontalHeader().resizeSection(1, 100)
        self.myDelegate = format.myCustomDelegate()
        self.tabs.table.view.setItemDelegate(self.myDelegate)

        # navigator
        if self.tabs.table.model.isPagingActive():
            self.navigatorLayout = QtGui.QGridLayout()
            self.navigatorLayout.setContentsMargins(0, 0, 0, 0)
            self.navigatorLayout.setObjectName("navigatorLayout")
            self.lNavSpacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
            self.firstToolButton = QtGui.QToolButton(self.tabs.table)
            self.firstToolButton.setObjectName("firstToolButton")
            self.firstToolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
            self.firstToolButton.setText('Awal')
            self.previousToolButton = QtGui.QToolButton(self.tabs.table)
            self.previousToolButton.setObjectName("previousToolButton")
            self.nextToolButton = QtGui.QToolButton(self.tabs.table)
            self.nextToolButton.setObjectName("nextToolButton")
            self.lastToolButton = QtGui.QToolButton(self.tabs.table)
            self.lastToolButton.setObjectName("lastToolButton")
            self.currentPageLineEdit = QtGui.QLineEdit(self.tabs.table)
            self.currentPageLineEdit.setObjectName("offsetLineEdit")
            self.totalPageLineEdit = QtGui.QLineEdit(self.tabs.table)
            self.totalPageLineEdit.setObjectName("totalPageLineEdit")
            self.totalPageLineEdit.setReadOnly(True)
            self.totalPageLineEdit.setMinimumSize(10, 22)
            self.totalPageLineEdit.setMaximumSize(46, 22)
            self.totalPageLineEdit.setText(unicode(self.tabs.table.model.page['count']))
            self.currentPageLineEdit.setText(unicode(self.tabs.table.model.page['current']))
            self.firstToolButton.clicked.connect(self.gotoFirstPage)
            self.previousToolButton.clicked.connect(self.gotoPrevPage)
            self.nextToolButton.clicked.connect(self.gotoNextPage)
            self.lastToolButton.clicked.connect(self.gotoLastPage)
            firstIcon = QtGui.QIcon()
            firstIcon.addPixmap(QtGui.QPixmap(":/go_first"), QtGui.QIcon.Normal, QtGui.QIcon.On)
            self.firstToolButton.setIcon(firstIcon)
            self.firstToolButton.setIconSize(QtCore.QSize(16, 18))
            previousIcon = QtGui.QIcon()
            previousIcon.addPixmap(QtGui.QPixmap(":/go_previous"), QtGui.QIcon.Normal, QtGui.QIcon.On)
            self.previousToolButton.setIcon(previousIcon)
            self.previousToolButton.setIconSize(QtCore.QSize(16, 18))
            nextIcon = QtGui.QIcon()
            nextIcon.addPixmap(QtGui.QPixmap(":/go_next"), QtGui.QIcon.Normal, QtGui.QIcon.On)
            self.nextToolButton.setIcon(nextIcon)
            self.nextToolButton.setIconSize(QtCore.QSize(16, 18))
            nextIcon.paint(QtGui.QPainter(), QtCore.QRect(), QtCore.Qt.AlignRight, QtGui.QIcon.Normal, QtGui.QIcon.On)        
            lastIcon = QtGui.QIcon()
            lastIcon.addPixmap(QtGui.QPixmap(":/go_last"), QtGui.QIcon.Normal, QtGui.QIcon.On)
            self.lastToolButton.setIcon(lastIcon)
            self.lastToolButton.setIconSize(QtCore.QSize(16, 18))        
            self.rNavSpacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
            self.navigatorLayout.addItem(self.lNavSpacerItem, 0, 0, 1, 1)
            self.navigatorLayout.addWidget(self.firstToolButton, 0, 1, 1, 1)
            self.navigatorLayout.addWidget(self.previousToolButton, 0, 2, 1, 1)
            self.navigatorLayout.addWidget(self.currentPageLineEdit, 0, 3, 1, 1)
            self.navigatorLayout.addWidget(self.totalPageLineEdit, 0, 4, 1, 1)
            self.navigatorLayout.addWidget(self.nextToolButton, 0, 5, 1, 1)
            self.navigatorLayout.addWidget(self.lastToolButton, 0, 6, 1, 1)
            self.navigatorLayout.addItem(self.rNavSpacerItem, 0, 7, 1, 1)

        # layout
        self.tabs.table.verticalLayout = QtGui.QVBoxLayout(self.tabs.table)
        self.tabs.table.verticalLayout.setContentsMargins(1, 1, 1, 1)
        self.tabs.table.verticalLayout.setObjectName("horizontalLayout")

        self.tabs.table.verticalLayout.addLayout(self.searchGridLayout)
        self.tabs.table.verticalLayout.addWidget(self.tabs.table.view)
        if self.tabs.table.model.isPagingActive():
            self.tabs.table.verticalLayout.addLayout(self.navigatorLayout)
        self.tabs.table.verticalLayout.addWidget(self.tabs.table.bottomButtonBox)

        # koneksi
        self.searchButton.clicked.connect(self.runSearch)
        self.searchLineEdit.done.connect(self.runSearch)
        self.clearSearchButton.clicked.connect(self.clearSearch)

        self.tabs.table.bottomButtonRefresh.clicked.connect(self.reloadView)
        self.tabs.table.model.signal.tableLoaded.connect(self.showPaging)

        # tab yang aktif sejak awal
        self.setCurrentIndex(0)

    def clearSearch(self):
        """
            Membersihkan kolom pencarian
        """
        self.searchLineEdit.clear()


    def runSearch(self):
        """
            Mencari produk berdasarkan keyword yang diberikan
        """
        if self.searchLineEdit.text != '':
            filterQuery = "produk LIKE '%" + self.searchLineEdit.text() + "%'"
            self.tabs.table.view.reset()
            self.tabs.table.model.model.reset()
            self.tabs.table.model.setFilter(filterQuery)


    def reloadView(self):
        """
            Memuat ulang tampilan sehingga tidak bertumpuk.
        """
        self.tabs.table.view.reset()
        self.tabs.table.model.model.reset()
        self.tabs.table.model.reloadModel()

    
    @QtCore.Slot(dict)
    def showPaging(self, page):
        print page
        if page.has_key('current'):
            self.totalPageLineEdit.setText(unicode(page['count']))
            self.currentPageLineEdit.setText(unicode(page['current']))

    def gotoFirstPage(self):
        if int(self.currentPageLineEdit.text()) > self.tabs.table.model.page['first']:
            self.tabs.table.model.loadPage(self.tabs.table.model.page['first'])


    def gotoPrevPage(self):
        if int(self.currentPageLineEdit.text()) > self.tabs.table.model.page['first']:
            self.tabs.table.model.loadPage(self.tabs.table.model.page['current'] - 1)


    def gotoNextPage(self):
        if int(self.currentPageLineEdit.text()) < self.tabs.table.model.page['last']:
            self.tabs.table.model.loadPage(self.tabs.table.model.page['current'] + 1)


    def gotoLastPage(self):
        if int(self.currentPageLineEdit.text()) < self.tabs.table.model.page['last']:
            self.tabs.table.model.loadPage(self.tabs.table.model.page['last'])


